package com.example.ecommercemanagesystem.controller;


import com.example.ecommercemanagesystem.dto.GoodsDto;
import com.example.ecommercemanagesystem.dto.GoodsDto2;
import com.example.ecommercemanagesystem.dto.MyMessage;
import com.example.ecommercemanagesystem.entity.Goods;
import com.example.ecommercemanagesystem.service.GoodsService;
import com.github.pagehelper.Page;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class GoodsController {
    @Resource
    private GoodsService goodsService;

    public GoodsService getGoodsService() {
        return goodsService;
    }

    public void setGoodsService(GoodsService goodsService) {
        this.goodsService = goodsService;
    }

    /**
     * 添加商品信息
     */

    @RequestMapping("/addGoods")
    public void addGoods(HttpServletRequest request, HttpServletResponse response, GoodsDto goodsDto) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //获取当前服务器所在的磁盘地址
        String path = request.getServletContext().getRealPath("/upload");
        System.out.println("上传的地址path" + path);
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String goods_picture = null;
        //获取当前上传的文件名,主图
        goods_picture = goodsDto.getGoods_picture().getOriginalFilename();
        //对该文件名进行重命名,主图
        goods_picture = System.currentTimeMillis() + "-" + goods_picture;
        //获取要上传文件的路径对象
        File file1 = new File(path + "/" + goods_picture);
        try {
            FileUtils.copyInputStreamToFile(goodsDto.getGoods_picture().getInputStream(), file1);
            System.out.println("文件上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("<script>alert('保存失败，发生异常');history.go(-1);</script>");
        }
        try {
            //注入值
            Goods goods = new Goods();
            goods.setGoods_info(goodsDto.getGoods_info());
            goods.setGoods_introduce(goodsDto.getGoods_introduce());
            goods.setGoods_picture(goods_picture);
            goods.setGoods_unit(goodsDto.getGoods_unit());
            goods.setGoods_price(goodsDto.getGoods_price());
            goods.setGoods_number(goodsDto.getGoods_number());
            goods.setGoods_type(goodsDto.getGoods_type());
            goods.setGoods_name(goodsDto.getGoods_name());
            goods.setGoods_time(goodsDto.getGoods_time());


            if (goodsService.insertGoods(goods)) {

                out.print("<script>alert('保存成功');location.href='goodslist';</script>");
            } else {
                out.print("<script>alert('保存失败');history.go(-1);</script>");
            }


        } catch (Exception e) {
            e.printStackTrace();
            out.print("<script>alert('保存失败');history.go(-1);</script>");
        }
    }

    /**
     * 获取所有商品信息
     *
     * @param size
     * @param page
     * @param goodsDto
     * @return
     */
    @RequestMapping("/getAllGoods")
    @ResponseBody
    public MyMessage getAllGoods(Integer size, Integer page, GoodsDto2 goodsDto) {

        Integer mypage = 1;
        Integer mysize = 3;
        MyMessage myMessage = new MyMessage();

        try {
            mypage = Integer.valueOf(page);
        } catch (Exception e) {

        }
        try {
            mysize = Integer.valueOf(size);
        } catch (Exception e) {

        }
        Long count = goodsService.queryGoodsCount(goodsDto);

        int maxpage = (int) (count % mysize == 0 ? (count / mysize) : (count / mysize + 1));

        //上限下限已经由pagehelper修正，不好用，我们自己修正
        mypage = mypage < 1 ? 1 : mypage;
        mypage = mypage > maxpage ? maxpage : mypage;


        Page<GoodsDto2> list = goodsService.queryGoods(goodsDto, page, size);
        myMessage.setData(list);
        myMessage.setPage(page);
        myMessage.setMaxPage(maxpage);
        myMessage.setSize(size);
        myMessage.setCode("200");
        myMessage.setFlag(1);
        myMessage.setInfo("查询成功");


        return myMessage;

    }

    /**
     * 根据id获取商品信息
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/getGoodsById")
    public String getGoodsById(String id, HttpServletRequest request) {
        Integer gid=Integer.valueOf(id);
        GoodsDto2 goodsDto2 = goodsService.getGoodsById(gid);
        request.setAttribute("goods", goodsDto2);
        return "editgoods";

    }

    /**
     * 修改商品信息
     * @param goodsDto
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/updateGoods")
    public void updateGoods(GoodsDto goodsDto, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //获取当前服务器所在的磁盘地址
        String path = request.getServletContext().getRealPath("/upload");
        System.out.println("上传的地址path" + path);
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        String goods_picture = null;
        //获取当前上传的文件名,主图
        goods_picture = goodsDto.getGoods_picture().getOriginalFilename();
        //对该文件名进行重命名,主图
        goods_picture = System.currentTimeMillis() + "-" + goods_picture;
        //获取要上传文件的路径对象
        File file1 = new File(path + "/" + goods_picture);
        try {
            FileUtils.copyInputStreamToFile(goodsDto.getGoods_picture().getInputStream(), file1);
            System.out.println("文件上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            out.print("<script>alert('保存失败，发生异常');history.go(-1);</script>");
        }
        try {
            //注入值
            GoodsDto2 goods = new GoodsDto2();
            goods.setGoods_id(goodsDto.getGoods_id());
            goods.setGoods_info(goodsDto.getGoods_info());
            goods.setGoods_introduce(goodsDto.getGoods_introduce());
            goods.setGoods_picture(goods_picture);
            goods.setGoods_unit(goodsDto.getGoods_unit());
            goods.setGoods_price(goodsDto.getGoods_price());
            goods.setGoods_number(goodsDto.getGoods_number());
            goods.setGoods_type(goodsDto.getGoods_type());
            goods.setGoods_name(goodsDto.getGoods_name());
            goods.setGoods_time(goodsDto.getGoods_time());


            if (goodsService.updateGoods(goods)) {

                out.print("<script>alert('修改成功');location.href='goodslist';</script>");
            } else {
                out.print("<script>alert('修改失败');history.go(-1);</script>");
            }


        } catch (Exception e) {
            e.printStackTrace();
            out.print("<script>alert('修改失败');history.go(-1);</script>");
        }

    }

    //导出excel文件
    @RequestMapping("/exportExcel")
    @ResponseBody
    public String exportExcel(HttpServletResponse response, Map<String, Object> params) {

        HSSFWorkbook workbook = goodsService.exportExcel(params);
        try {
            if (response != null) {
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                        "attachment;filename=\"" + new String(("商品数据信息" + ".xls").getBytes("gb2312"), "ISO8859-1"));
                OutputStream out = response.getOutputStream();
                workbook.write(out);
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
